package dt

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"fmt"
	"encoding/json"
	"analysis-ss/models"
)

type Course struct {
	DataTable
}

func (cs *Course) GetTableInfo(start, length int, args ...string) error {
	childId := ""
	courseId := ""
	argsLen := len(args)
	if argsLen > 1 {
		childId = args[0]
		courseId = args[1]
	} else if argsLen == 1 {
		childId = args[0]
	}

	beego.Debug("childID ", childId, "COUNT ", courseId)
	// 起始位置和当前页面信息
	cs.Start = start
	cs.Length = length

	// 记录总数
	count, err := QueryCourseTotal(childId, courseId)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.RecordsTotal = count
	cs.RecordsFiltered = count

	// 当前记录信息
	centers := GetCourseList(childId, courseId, start, length)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.Data = centers

	return nil
}

func QueryCourse(childId interface{}, courseId string, start, length int) ([]models.ScheduleDetailChild, int64, error) {
	var courses []models.ScheduleDetailChild
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
	               sc.child_id,
	               sc.schedule_id as id,
	               s.course_name,
	               s.teacher_name,
	               s.start_time,
	               s.end_time,
	               s.week
             FROM
                   t_schedule_child sc
             LEFT JOIN
                    t_schedule s on s.id=sc.schedule_id
             WHERE
                    sc.child_id= ?  and  s.course_id =4`
	//if courseId != "0" && courseId != "" {
	//	sqlStr = fmt.Sprint(sqlStr, " and  s.course_id =", courseId)
	//}
	sqlStr = fmt.Sprint(sqlStr, " order by  s.start_time desc limit ", start, ",", length)
	num, err := o.Raw(sqlStr, childId).QueryRows(&courses)
	return courses, num, err
}

func QueryCourseScore(childId interface{}, scheduleId interface{}) ([]models.Score, int64, error) {
	var Scores []models.Score
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                 p.id, p.name, s.score, s.memo
             FROM
                  t_project p
           LEFT JOIN
                   t_schedule_project_score s ON s.project_id=p.id
             WHERE
                   s.child_id = ? AND s.schedule_id = ?;`
	num, err := o.Raw(sqlStr, childId, scheduleId).QueryRows(&Scores)
	return Scores, num, err
}

func QueryCourseProQus(childId interface{}, scheduleId interface{}) ([]models.Score, int64, error) {
	var Scores []models.Score
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                 p.id, p.name
             FROM
                    t_project p
            LEFT JOIN
                    t_schedule_child_project sc ON p.id =sc.project_id
             WHERE
                   sc.child_id = ? AND sc.schedule_id = ?;`
	num, err := o.Raw(sqlStr, childId, scheduleId).QueryRows(&Scores)
	return Scores, num, err
}

func QueryCourseTotal(childId interface{}, courseId string) (int, error) {
	var Total int
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                count(*)
             FROM
                 t_schedule t
             LEFT JOIN
                 t_schedule_child sc ON sc.schedule_id = t.id
             WHERE
                  sc.child_id = ?  `
	if courseId != "0" && courseId != "" {
		sqlStr = fmt.Sprint(sqlStr, " and  t.id =", courseId)
	}
	err := o.Raw(sqlStr, childId).QueryRow(&Total)
	return Total, err
}

func QueryChildCode(childId interface{}) ([]models.ChildAbilityFeedbackConfig, error) {
	var codeNames []models.ChildAbilityFeedbackConfig
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT DISTINCT(si.name) as code_name,si.code
                   FROM
                   schedule_project_subject sub
                   LEFT JOIN
                   sensory_integration si ON si.code = sub.project_code
                   WHERE
                   sub.child_id = ?;`
	_, err := o.Raw(sqlStr, childId).QueryRows(&codeNames)
	return codeNames, err
}

// 查找孩子的测评信息
func QueryChildRecord(childId interface{}) (models.StudyAbilityReport, error) {
	var Record models.StudyAbilityReport
	o := orm.NewOrm()
	o.Using("record")
	sqlStr := `SELECT
	        stu_id as id,
		qiantingpingheng,
		bentigan,
		chujuefangyu,
		tingjuejiyiguangdu,
		tingjuechangshijiyi,
		shifenbianshiwulv,
		shijueguangdu,
		shidongtonghenengli,
		yuedusudu,
		cuowulv,
		yuedulijiezhengquelv,
		kouyubiaodanengli,
		siweifenshu,
		baifendengji
	        FROM
	        study_ability_report
	        where
	        stu_id = ?;`
	err := o.Raw(sqlStr, childId).QueryRow(&Record)
	return Record, err
}

// 查看孩子的所有的配置
func QueryChildCodeConfig(childId, code interface{}) ([]models.ChildAbilityFeedbackConfig, error) {
	var configs []models.ChildAbilityFeedbackConfig
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                  c.id, c.child_id, c.code, c.name, c.value, s.name as code_name
                  FROM
                  child_ability_feedback_config c
                  LEFT JOIN
                  sensory_integration s ON s.code = c.code
                   WHERE
                   c.child_id = ? AND c.code = ?;`
	_, err := o.Raw(sqlStr, childId, code).QueryRows(&configs)
	return configs, err
}

// 查看孩子的配置
func QueryChildConfig(childId, code, codeStr interface{}) ([]models.ChildAbilityFeedbackConfig, error) {
	var configs []models.ChildAbilityFeedbackConfig
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                   id, child_id, code, name, value
                   FROM
                   child_ability_feedback_config
                   WHERE
                   child_id = ?
                   AND code in (?,?);`
	_, err := o.Raw(sqlStr, childId, codeStr, code).QueryRows(&configs)
	return configs, err
}

// 查看孩子的项目的训练次数
func QueryChildCodeXLCS(childId, code interface{}) (string, error) {
	var times string
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `SELECT
                   COUNT(*)
                   FROM
                   schedule_project_subject
                   WHERE
                   child_id = ？
                   AND project_code = ？;`
	err := o.Raw(sqlStr, childId, code).QueryRow(&times)
	return times, err
}

//课程数据
func GetCourseList(childId interface{}, courseId string, start, length int) []models.ScheduleDetailChild {
	//查询所有的中心
	courses, _, err := QueryCourse(childId, courseId, start, length)
	if err != nil {
		beego.Debug(err)
	}
	for i := 0; i < len(courses); i++ {
		courses[i].Date = getCourseDate(courses[i].StartTime)
		courses[i].WeekStr = getCourseWeek(courses[i].Week)
		courses[i].CourseTime = getCourseTime(courses[i].StartTime, courses[i].EndTime)
		courses[i].Status = getStatus(courses[i].SignType)
		courses[i].Score = getScore(childId, courses[i].Id)
	}
	return courses
}

// 获得日期 todo 看有没有更好的方式去转化日期
func getCourseDate(time string) string {
	date := "日期异常"
	if len(time) > 8 {
		y := time[0:4]
		m := time[4:6]
		d := time[6:8]
		date = fmt.Sprint(y, "年", m, "月", d, "日")
	}
	return date
}

func getCourseWeek(week int) string {
	weekStr := "未知"
	switch week {
	case 1:
		weekStr = "星期一"
	case 2:
		weekStr = "星期二"
	case 3:
		weekStr = "星期三"
	case 4:
		weekStr = "星期四"
	case 5:
		weekStr = "星期五"
	case 6:
		weekStr = "星期六"
	case 7:
		weekStr = "星期日"
	}
	return weekStr
}

// 组合上课时间
func getCourseTime(starTime, endTime string) string {
	courseTime := "未知"
	// 获得上课日期
	starTimeStr := getTime(starTime)
	endTimeStr := getTime(endTime)
	courseTime = fmt.Sprint(starTimeStr, "-", endTimeStr)
	return courseTime
}

func getTime(time string) string {
	timeStr := "未知"
	if len(time) > 12 {
		hours := time[8:10]
		min := time[10:12]
		timeStr = fmt.Sprint(hours, ":", min)
	}
	return timeStr
}

// 转化签到状态
func getStatus(status int) string {
	statusStr := "无状态"
	switch status {
	case 1:
		statusStr = "签到"
	case 2:
		statusStr = "请假"
	case 3:
		statusStr = "旷课"
	}
	return statusStr
}

// 获得成绩
func getScore(childId interface{}, scheduleId interface{}) string {
	scoreStr := ""
	qus, num, err := QueryCourseProQus(childId, scheduleId)
	if err != nil {
		beego.Debug(err)
	}
	if num > 0 {
	scores, _, err := QueryCourseScore(childId, scheduleId)
	if err != nil {
		beego.Debug(err)
	}

		for _, qV := range qus {
			memo := "暂时没有评价"
			score := "暂时没有成绩"
			for _, qS := range scores {
				if qS.Id == qV.Id {
					score = getAns(qS.Score)
				}
			}
			scoreStr = fmt.Sprint(scoreStr, "<div style='width: 100%;'><div style='display: inline-block;width: 70%;'><b>",
				qV.Name, ":</b>&nbsp;&nbsp;", score, "</div><div style='display: inline-block;width: 30%;'><b>备注</b>:&nbsp;", memo, "</div></div>")
		}
	}
	return scoreStr
}

// 解析json数组
func getAns(score string) string {
	var grades string
	var scoreResult []map[string]interface{}
	if err := json.Unmarshal([]byte(score), &scoreResult); err != nil {
		beego.Info("错误")
	}
	for _, v := range scoreResult {
		if v["type"] != "" && v["type"] != nil {
			descStr := v["type"]
			switch descStr {
			case "leave":grades += fmt.Sprint( "通过等级 : ")
			case "star":grades += fmt.Sprint( "星星个数 : ")
			case "time":grades += fmt.Sprint( "时间   : ")
			}
		}
		if v["value"] != "" && v["value"] != nil {
			grades += fmt.Sprint(v["value"])
		}
	}
	return grades
}
